package com.wuhanpe.leafid.controller

import com.wuhanpe.leafid.service.SegmentService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import com.wuhanpe.leafid.entity.Result
import com.wuhanpe.leafid.exception.LeafServerException
import com.wuhanpe.leafid.exception.NoKeyException
import com.wuhanpe.leafid.model.Status

/**
 * @author zooy
 * @since 2025/9/12-15:44
 */
@RestController
@RequestMapping("/api")
class LeafController {

    @Autowired
    lateinit var segmentService: SegmentService

    @RequestMapping(value = ["/segment/get/{key}"])
    fun getSegmentId(@PathVariable("key") key: String): String? {
        return get(key, segmentService.getId(key))
    }

    private fun get(@PathVariable("key") key: String, id: Result): String? {
        val result: Result
        if (key == null || key.isEmpty()) {
            throw NoKeyException()
        }
        result = id
        if (result.status == Status.EXCEPTION) {
            throw LeafServerException(result.toString())
        }
        return result.id.toString()
    }

}
